#!/usr/bin/perl

use strict;
use warnings;
$|++;

use Getopt::Long;
use Config::Simple;

use Shell qw/touch date/;

use IO::File;
use Data::Dumper;

use Fcntl ':flock';

my $VERSION="1.00";
my $configFile=undef;
my $dataFile=undef;
my $opt = GetOptions (
        "f|config=s" => \$configFile,    # string
        "d|data=s" => \$dataFile,
        );  # flag

unless ( defined ($configFile) and -f $configFile ) {
    print STDERR "Config file doesn't exists or is not defined !\n";
    exit 1;
}

unless ( defined ($dataFile) and -f $dataFile ) {
    print STDERR "Data file doesn't exists or is not defined !\n";
    exit 2;
}

my %ini;
tie %ini, "Config::Simple", $configFile;

my $verbose=$ini{'general.verbose'};
print Dumper %ini if $verbose;

my $i=1;

my %includeOutput=();
my %excludeOutput=();
my @allHandlers=();

while ( $ini{"output$i.file"} ) {
	print "\t* output $i => ",  retrieveTrueFileName( $ini{"output$i.file"}), "\n" if $verbose;
	print "\t* ", $ini{"output$i.mode"}, " mode\n" if $verbose; 
	my $lfh=openFileHandle ($ini{"output$i.file"}, $ini{"output$i.zipped"});
	if (	 $ini{"output$i.mode"} eq "include" ) {
		print "\n\t adding include filehandle from : ", $ini{"output$i.file"};
		push @{$includeOutput{ $ini{"output$i.pattern"} }}, $lfh;
	}
	if (	 $ini{"output$i.mode"} eq "exclude" ) {
		print "\n\t adding exclude filehandle from : ", $ini{"output$i.file"};
		push @{$excludeOutput{ $ini{"output$i.pattern"} }}, $lfh;
	}
	push @allHandlers, $lfh;
	$i++;
}

print Dumper %includeOutput if $verbose;

open( my $dfh, "< $dataFile" )
or die "Couldn't open $dataFile for reading: $!\n";

while (<$dfh>) {
	print if $verbose;
	for my $k ( keys ( %includeOutput) ) {
		print "\n\t * Analyse $k pattern" if $verbose;
		if ( /$k/) {
			foreach my $lfh (@{$includeOutput{$k}}) {
				print "\n\t\t* Writing in $lfh" if $verbose;
				print $lfh $_;
			}
		}
	}
	for my $k ( keys ( %excludeOutput) ) {
		print "\n\t * Analyse $k pattern" if $verbose;
		unless ( /$k/) {
			foreach my $lfh (@{$excludeOutput{$k}}) {
				print "\n\t\t* Writing in $lfh" if $verbose;
				print $lfh $_;
			}
		}
	}

}
close $dfh;

exit 0;



sub trim {
    my $string = shift;
    $string="" unless defined ($string);
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}

sub retrieveTrueFileName{
    my $name=shift;
    $name =~ s/(\%.)-(\d+)/date( "--date \"$2 day ago\"", "+$1")/eg;
    $name =~ s/(\%.)/date("+$1")/eg;
    $name =~ s/\n//g;

    return $name;
}

sub openFileHandle {
    my $file= retrieveTrueFileName shift;
    my $zipped=shift;
    my $handle = new IO::File;
    if (defined $zipped and $zipped==1) {
        open ($handle, "| gzip >> $file.gz"); #  we write to a pipe 
    } else {
        touch $file unless ( -f $file );
        die "$file : $@" unless ( -f $file );
        open($handle, ">>$file") or die "$file: $!";
    }
    $handle->autoflush(1);
    ### FILE : $file
    ### HANDLER: $handle
    return $handle;
}
